//
//  CheekVodepViewController.m
//  CheekiOS
//
//  Created by mac on 2017/5/9.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "CheekVodepViewController.h"

//遇见过的人
#import "XLPhotoCell.h"
#import "XLLayout.h"
//腾讯云
#import <ILiveSDK/ILiveLoginManager.h>
#import <AVFoundation/AVFoundation.h>
//视频界面
#import "LiveViewController.h"
//筛选界面
#import "CheekScreeningController.h"
//遇到过的人界面
#import "CheekEncounterViewController.h"
//弹框
#import "CheekMessageAlertView.h"
//充值
#import "UserAccountViewController.h"
//聊天界面
#import "HQConversationViewController.h"


@interface CheekVodepViewController ()<UICollectionViewDelegate, UICollectionViewDataSource,XLPhotoCellDelegate,CheekMessageAlertViewDelegate>

/**
 *  图片数组
 */
@property (nonatomic, strong) NSMutableArray *dateSource;
/** 页数*/
@property (nonatomic, assign)NSInteger page;
/** 数量 */
@property (nonatomic, assign)NSInteger rows;

@property (nonatomic, strong)UICollectionView *collection;
//个人信息数据
@property (nonatomic, strong)UserpersionlInfoModel *model;
//弹框
@property (nonatomic, strong)CheekMessageAlertView *messageAlert;
//第几个Cell上的聊天按钮被点击
@property (nonatomic, assign)NSInteger integerPath;
//当前钻石
@property (nonatomic, strong)UserInfocharmModel *charmModel;

@property (nonatomic, strong)UIImageView *VodepUserImg;

@property (nonatomic, strong)NSNumber *UserTypehidden;
@end

static NSString * titleCellident = @"titleCell";
@implementation CheekVodepViewController



- (void)viewDidLoad {
    [super viewDidLoad];

    _integerPath = 0;
    UIButton *screeningBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [screeningBtn addTarget:self action:@selector(screeningBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [screeningBtn setImage:[UIImage imageNamed:@"viedo_search_icon"] forState:UIControlStateNormal];
    [screeningBtn setTitle:@"筛选性别、人群等" forState:UIControlStateNormal];
    screeningBtn.titleLabel.font = FontP(17);
    [screeningBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    screeningBtn.frame = CGRectMake(15, 0, KScreenWidth, 44*SCREEN_WIDTH_RATIO47);
    
    screeningBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    screeningBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

    UIBarButtonItem *backItem = [[UIBarButtonItem alloc ] initWithCustomView:screeningBtn];
    self.navigationItem.leftBarButtonItem = backItem;
 
    
    UIImageView *imgView = [[UIImageView alloc] init];
    imgView.image = [UIImage imageNamed:@"jiantou2"];
    imgView.frame =CGRectMake(KScreenWidth-40, 15*SCREEN_WIDTH_RATIO47, 20*SCREEN_WIDTH_RATIO47, 20*SCREEN_WIDTH_RATIO47);
    [self.view addSubview:imgView];
    
    
    
    UIButton *encounterButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [encounterButton addTarget:self action:@selector(encounterButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [encounterButton setTitle:@"遇到的人" forState:UIControlStateNormal];
    [encounterButton setTitleColor:RGB(110, 110, 110) forState:UIControlStateNormal];
    encounterButton.frame = CGRectMake(0, 0, KScreenWidth, 50*SCREEN_WIDTH_RATIO47);
    encounterButton.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    encounterButton.backgroundColor = [UIColor clearColor];
    encounterButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
    [self.view addSubview:encounterButton];
    
    
    
    CGFloat VodepUserImgW ;
    CGFloat VodepUserImgH ;
    CGFloat VodepUserImgX ;
    CGFloat VodepUserImgY ;
    CGFloat collectionW ;
    CGFloat collectionH ;
    CGFloat itemSizeH;
    CGFloat itemSizeW;

    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad){
        NSLog(@"ipad");
        VodepUserImgX = 80*SCREEN_WIDTH_RATIO47;
        VodepUserImgY =encounterButton.bottom+20*SCREEN_WIDTH_RATIO47;
        VodepUserImgW = KScreenWidth-160*SCREEN_WIDTH_RATIO47;
        VodepUserImgH = VodepUserImgW;
        collectionW = self.view.frame.size.width;
        collectionH = 210*SCREEN_WIDTH_RATIO47;
        itemSizeW = 180*SCREEN_WIDTH_RATIO47;
        itemSizeH = 200*SCREEN_WIDTH_RATIO47;
    }else{
        VodepUserImgW = KScreenWidth-30*SCREEN_WIDTH_RATIO47;
        VodepUserImgH = 300*SCREEN_WIDTH_RATIO47;
        VodepUserImgX = 15*SCREEN_WIDTH_RATIO47;
        VodepUserImgY =encounterButton.bottom+20*SCREEN_WIDTH_RATIO47;
        collectionW = self.view.frame.size.width;
        collectionH = 330*SCREEN_WIDTH_RATIO47;
        itemSizeW = 200*SCREEN_WIDTH_RATIO47;
        itemSizeH = 300*SCREEN_WIDTH_RATIO47;
        NSLog(@"iphone or ipod");
    }
    
    
    self.VodepUserImg = [[UIImageView alloc] initWithFrame:CGRectMake(VodepUserImgX, VodepUserImgY, VodepUserImgW, VodepUserImgH)];
    self.VodepUserImg.hidden = YES;
    self.VodepUserImg.image = [UIImage imageNamed:@"viedo_met_ai"];
    self.VodepUserImg.contentMode = UIViewContentModeScaleToFill;
    [self.view addSubview:self.VodepUserImg];
    

    // 创建布局
    XLLayout *layout = [[XLLayout alloc] init];
    layout.itemSize = CGSizeMake(itemSizeW, itemSizeH);
    
    
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, encounterButton.bottom, collectionW, collectionH) collectionViewLayout:layout];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.backgroundColor = [UIColor clearColor];
    [self.collection setShowsHorizontalScrollIndicator:NO];

    [self.view addSubview:self.collection];
    
    
    [self.collection registerClass:[XLPhotoCell class] forCellWithReuseIdentifier:titleCellident];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, self.collection.bottom+20*SCREEN_WIDTH_RATIO47, KScreenWidth, 30*SCREEN_WIDTH_RATIO47)];
    label.text = @"点击遇见更多人吧";
    label.textColor = ColorI(0x2e353f);
    label.font = FontP(17);
    label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label];
    
    UIButton *VideoLivebutton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [VideoLivebutton setBackgroundImage:[UIImage imageNamed:@"viedo_connect_icon"] forState:UIControlStateNormal];
    
    [VideoLivebutton addTarget:self action:@selector(VideoLivebuttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    VideoLivebutton.frame = CGRectMake(self.view.centerX-60*SCREEN_WIDTH_RATIO47, label.bottom+9*SCREEN_WIDTH_RATIO47, 120*SCREEN_WIDTH_RATIO47, 120*SCREEN_WIDTH_RATIO47);
    
    VideoLivebutton.adjustsImageWhenHighlighted = NO;//按钮点击后的阴影效果
    [self.view addSubview:VideoLivebutton];
    
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
    [self setNavgationBarHiddenNo];
    [self requestgetCommonOpen ];
    [self UserInfoRequestDate];
    [self requestDate];
}
- (void)requestgetCommonOpen{
    
    [HcardHttpmanager getCommonOpen:[HQHttpManager getUserId] success:^(id result) {
        if([result[@"code"] isEqualToString:@"ok"]){
            
            _UserTypehidden = result[@"res"][@"open"];
            [self.collection reloadData];

            
            
            
        }
        
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)UserInfoRequestDate{
    
    [HcardHttpmanager getPersionalUserInfosuccess:^(id sucess) {
        self.model = [UserpersionlInfoModel mj_objectWithKeyValues:sucess[@"res"]];

    } failure:^(NSError *error) {
        
    }];

}

- (void)requestDate{
    
    _page = 1;
    _rows = 10;
    
    _dateSource = [NSMutableArray array];
    [CheekVodeRequest getCheekVideoChatListUid:[HQHttpManager getUserId] page:_page rows:_rows success:^(id sucess) {
        
        if ([sucess[@"code"] isEqualToString:@"ok"]) {
            _dateSource = [CheekVodeModel mj_objectArrayWithKeyValuesArray:sucess[@"res"]];
            
            if (_dateSource.count >0) {
                self.VodepUserImg.hidden = YES;
            }else{
                self.VodepUserImg.hidden = NO;
            }
            
            [self.collection reloadData];

        }
  
        
    } failure:^(NSError *error) {
        self.VodepUserImg.hidden = NO;

        self.VodepUserImg.image = [UIImage imageNamed:@"network_outage_illustration"];
        
    }];
    
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dateSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    XLPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:titleCellident forIndexPath:indexPath];
    cell.delegate = self;
    CheekVodeModel *model = _dateSource[indexPath.row];
    cell.indexPath = indexPath;
    cell.model = model;

    return cell;
    
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击的item---%zd",indexPath.item);
}
#pragma mark ===============删除  发送消息================
-(void)removeBtnClick:(UIButton *)sender{
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定删除吗?" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSInteger index = sender.tag;
        
        CheekVodeModel *model = _dateSource[index];
        
        [CheekVodeRequest getCheekDelVideoUid:[HQHttpManager getUserId] Wid:model.uid empty:@"" success:^(id sucess) {
            
            if ([sucess[@"code"] isEqualToString:@"ok"]) {
                [self.dateSource removeObjectAtIndex:index];
                
                [self.collection reloadData];
            }
            
            
        } failure:^(NSError *error) {
            
        }];

    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertVC addAction:confirAction];
    [alertVC addAction:cancel];
    [self.navigationController presentViewController:alertVC animated:YES completion:nil];

}

//点击聊天
-(void)indexBannerSubiew:(XLPhotoCell *)subiew MessageBtnClick:(UIButton *)sender{

    _integerPath = subiew.indexPath.row;


        CheekVodeModel *model = _dateSource[_integerPath];
        
        if ([model.moneyStatus isEqualToString:@"1"]) {
            HQConversationViewController *conversationVC = [[HQConversationViewController alloc]init];
            conversationVC.conversationType = ConversationType_PRIVATE;
            NSString *str = model.uid;
            conversationVC.targetId = [NSString stringWithFormat:@"%@",str];
            conversationVC.title = model.nickName;
            conversationVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:conversationVC animated:YES];

        }else{
            
            if ([_UserTypehidden isEqualToNumber:@1]) {
                [self messageAlertAction];

            }else{
                HQConversationViewController *conversationVC = [[HQConversationViewController alloc]init];
                conversationVC.conversationType = ConversationType_PRIVATE;
                NSString *str = model.uid;
                conversationVC.targetId = [NSString stringWithFormat:@"%@",str];
                conversationVC.title = model.nickName;
                conversationVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:conversationVC animated:YES];

            }
            

        }

}
//弹框
- (void)messageAlertAction{

    self.messageAlert = [[CheekMessageAlertView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    self.messageAlert.delegate = self;
    
    if (self.model.charm > 20) {
        [self.messageAlert CheekAlertTitle:@"需要花费20钻石" text:@"和TA【视频聊天】和【文字聊天】" determineTitle:@"确定" determineBtnTage:1];
    }else{
        [self.messageAlert CheekAlertTitle:@"需要花费20钻石" text:@"和TA【视频聊天】和【文字聊天】" determineTitle:@"去购买" determineBtnTage:0];
    }
    [self animationWithView:self.messageAlert duration:0.3];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.messageAlert.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];

        
        [self.view addSubview:self.messageAlert];
    }];
 
}
//取消
-(void)removeBtn:(UIButton *)sender{
    self.messageAlert.hidden = YES;
    [self.messageAlert removeFromSuperview];
}
//确定
-(void)determine:(UIButton *)sender{
    
  
    self.messageAlert.hidden = YES;

        [self.messageAlert removeFromSuperview];

        
        [HcardHttpmanager getuserInfocharmsuccess:^(id sucess) {
            UserInfocharmModel *model = sucess;
            NSInteger modelCharm = [model.charm intValue];
            NSInteger charm = 20;
            if (modelCharm >= charm) {
                
                CheekVodeModel *model = _dateSource[_integerPath];
              
                [CheekVodeRequest getCheekVideobeFriendUid:[HQHttpManager getUserId] Wid:model.uid charm:@"20" success:^(id sucess) {
                    
                    if ([sucess[@"code"] isEqualToString:@"ok"]) {
                        
                        HQConversationViewController *conversationVC = [[HQConversationViewController alloc]init];
                        conversationVC.conversationType = ConversationType_PRIVATE;
                        NSString *str = model.uid;
                        conversationVC.targetId = [NSString stringWithFormat:@"%@",str];
                        conversationVC.title = model.nickName;
                        conversationVC.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:conversationVC animated:YES];
                    }
                    
                } failure:^(NSError *error) {
                    
                }];
                
            }else{
            
                UserAccountViewController *vc = [[UserAccountViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            
            }
        } failure:^(NSError *error) {
            
        }];
  
    
}
- (void)animationWithView:(UIView *)view duration:(CFTimeInterval)duration{
    
    CAKeyframeAnimation * animation;
    animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = duration;
    animation.removedOnCompletion = NO;
    
    animation.fillMode = kCAFillModeForwards;
    
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    //    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 0.9)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    
    animation.values = values;
    animation.timingFunction = [CAMediaTimingFunction functionWithName: @"easeInEaseOut"];
    
    [view.layer addAnimation:animation forKey:nil];
}
#pragma mark ============跳转到视频界面=========
- (void)VideoLivebuttonAction:(UIButton *)button{
    
    AVAuthorizationStatus videoStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(videoStatus == AVAuthorizationStatusRestricted || videoStatus == AVAuthorizationStatusDenied)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"您没有相机使用权限,请到 设置->隐私->相机 中开启权限" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *confirAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:confirAction];
        [self.navigationController presentViewController:alertVC animated:YES completion:nil];
        return;
    }
    AVAuthorizationStatus audioStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if(audioStatus == AVAuthorizationStatusRestricted || audioStatus == AVAuthorizationStatusDenied)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"您没有麦克风使用权限,请到 设置->隐私->麦克风 中开启权限" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *confirAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:confirAction];
        [self.navigationController presentViewController:alertVC animated:YES completion:nil];
        return;
    }

    

        LiveViewController *vc = [[LiveViewController alloc] init];
        vc.Sex = @"2";
        [self presentViewController:vc animated:YES completion:nil];
        

   
        
    
  
}
#pragma mark =================跳转到搜索页面===============
- (void)screeningBtnAction{
    CheekScreeningController *Vc = [[CheekScreeningController alloc] init];
    
    [self.navigationController pushViewController:Vc animated:YES];
}
//遇到的人
- (void)encounterButtonAction{
    CheekEncounterViewController *vc = [[CheekEncounterViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
@end
